package org.example;


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcInsertCode1 {
    static Connection con;
    static {

        Properties properties = new Properties();
        try {
            properties.load(new BufferedReader(new FileReader("first_git/src/main/resources/local_mysql.properties")));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        try {
            Class.forName(properties.getProperty("Driver"));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            con = DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void insert() throws FileNotFoundException, SQLException,IOException {
        String sql = "insert into car_info values (?,?,?,?,?,?,?,?,?)";
        BufferedReader bufferedReader = new BufferedReader(new FileReader("first_git/src/data/cars.csv"));
        String lines ;
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        int count=1;
        while ((lines=bufferedReader.readLine())!=null){
           String[] split = lines.split(",");
           for(int i =0;i<9;i++){
               preparedStatement.setString(i+1,split[i]);
           }
            preparedStatement.executeUpdate();
            System.out.println(String.format("第%d条数据插入成功",count++));
        }
    }
    public static void main(String[] args) throws SQLException, IOException {
        insert();
    }
}
